package com.weixin.engine.daily.guava;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

import java.util.concurrent.TimeUnit;

public class TestGuavaCache {

    public static void main(String[] args) {
        RemovalListener<String, String> removalListener = new RemovalListener<String, String>() {
            @Override
            public void onRemoval(RemovalNotification<String, String> removalNotification) {
                System.out.println(removalNotification.getKey() + " : " + removalNotification.getValue() + "   has been removed");
            }
        };

        Cache<String, String> cache = CacheBuilder
                .newBuilder()
//                .expireAfterAccess(5, TimeUnit.SECONDS)
                .expireAfterWrite(5, TimeUnit.SECONDS)
                .removalListener(removalListener)
                .build();

        cache.put("1", "1");
        cache.put("2", "2");
        cache.put("3", "3");
        cache.put("4", "4");
        cache.put("5", "5");


        System.out.println("get : " + cache.getIfPresent("1"));
        System.out.println("get : " + cache.getIfPresent("2"));
        System.out.println("get : " + cache.getIfPresent("3"));
        System.out.println("get : " + cache.getIfPresent("4"));
        System.out.println("get : " + cache.getIfPresent("5"));

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        cache.cleanUp();
//        cache.invalidate("1");

        System.out.println("get : " + cache.getIfPresent("1"));
        System.out.println("get : " + cache.getIfPresent("2"));
        System.out.println("get : " + cache.getIfPresent("3"));
        System.out.println("get : " + cache.getIfPresent("4"));
        System.out.println("get : " + cache.getIfPresent("5"));
        System.out.println("size : " + cache.size());
    }
}